package com.yzf.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysql.cj.xdevapi.Collection;
import com.yzf.common.R;
import com.yzf.dto.DishDto;
import com.yzf.entity.Category;
import com.yzf.entity.Dish;
import com.yzf.entity.DishFlavor;
import com.yzf.entity.Employee;
import com.yzf.service.CategoryService;
import com.yzf.service.DishFlavorService;
import com.yzf.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author yzf
 * @description
 * @since 2023/2/15 22:39
 */
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        // 分页构造器
        Page<Dish> pg = new Page(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        // 条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        // 添加过滤条件
        queryWrapper.like(name!=null,Dish::getName,name);
        // 添加拍序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(pg, queryWrapper);
        // 对象拷贝
        BeanUtils.copyProperties(pg,dishDtoPage,"records");

        List<Dish> records = pg.getRecords();
        List<DishDto> list=records.stream().map((itm)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(itm,dishDto);
            Long categoryId = itm.getCategoryId();// 分类ID
            // 根据id查询分类对象
            Category byId = categoryService.getById(categoryId);
            dishDto.setCategoryName(byId.getName());
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        // 清理所有菜品的缓存数据
//        Set<String> keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
        // 清理某个分类下的菜品缓存数据
        String key="dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success("添加菜品成功");
    }

    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){
        DishDto dishDto = new DishDto();
        Dish dish = dishService.getById(id);
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(id!=null,DishFlavor::getDishId,id);
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(list);
        BeanUtils.copyProperties(dish,dishDto);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        // 清理所有菜品的缓存数据
//        Set<String> keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
        // 清理某个分类下的菜品缓存数据
        String key="dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success("修改成功");
    }

//    @GetMapping("/list")
//    public R<List<Dish>> list(String categoryId){
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(categoryId!=null,Dish::getCategoryId,categoryId);
//        queryWrapper.orderByDesc(Dish::getUpdateTime);
//        List<Dish> list = dishService.list(queryWrapper);
//        return R.success(list);
//    }

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> dtoList=null;
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        // 获取Redis缓存中的数据
        dtoList=(List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dtoList!=null){
            // 如果Redis缓存中存在则直接返回缓存中的数据
            return R.success(dtoList);
        }
        // 如果不存在,需要查询数据库,将查询数据缓存到Redis中
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
            dtoList=list.stream().map((itm)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(itm,dishDto);
            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DishFlavor::getDishId,itm.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(wrapper);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
        // 如果不存在,需要查询数据库,将查询数据缓存到Redis中
            redisTemplate.opsForValue().set(key,dtoList,30, TimeUnit.MINUTES);
        return R.success(dtoList);
    }
}
